package Phaser_7;
import java.util.concurrent.Phaser;
public class 复杂协调_分布式计算模拟 {
    public static void main(String[] args) {
        final int NODES = 5;
        final Phaser computationPhaser = new Phaser(NODES);
        final Phaser validationPhaser = new Phaser(1); // 主验证线程
        // 计算节点
        for (int i = 0; i < NODES; i++) {
            final int nodeId = i;
            new Thread(new Runnable() {
                public void run() {
                    // 计算阶段
                    try {
                        System.out.println("节点" + nodeId + " 开始计算");
                        Thread.sleep((long)(Math.random() * 1500 + 500));
                        System.out.println("节点" + nodeId + " 计算完成");
                        computationPhaser.arriveAndAwaitAdvance();

                        // 注册到验证阶段
                        validationPhaser.register();
                        System.out.println("节点" + nodeId + " 等待验证结果");
                        validationPhaser.arriveAndAwaitAdvance();

                        System.out.println("节点" + nodeId + " 收到验证结果");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        // 主验证线程
        new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println("验证线程等待所有计算完成...");
                    computationPhaser.awaitAdvance(computationPhaser.getPhase());

                    System.out.println("开始验证计算结果...");
                    Thread.sleep(2000);
                    System.out.println("验证完成，通知所有节点");

                    validationPhaser.arriveAndDeregister();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}